package com.wans.guli.ware.controller;

import java.util.*;
import java.util.stream.Collectors;

// import org.apache.shiro.authz.annotation.RequiresPermissions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.wans.guli.ware.entity.WareSkuEntity;
import com.wans.guli.ware.service.WareSkuService;
import com.wans.guli.common.utils.PageUtils;
import com.wans.guli.common.utils.R;


/**
 * 商品库存
 *
 * @author wans
 * @email wansconst@163.com
 * @date 2025-08-01 16:31:00
 */
@RestController
@RequestMapping("ware/waresku")
@Slf4j
public class WareSkuController {
    @Autowired
    private WareSkuService wareSkuService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("ware:waresku:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = wareSkuService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    //@RequiresPermissions("ware:waresku:info")
    public R info(@PathVariable("id") Long id) {
        WareSkuEntity wareSku = wareSkuService.getById(id);

        return R.ok().put("wareSku", wareSku);
    }

    /**
     * 根据sku批量扣减库存
     */
    @PostMapping("/stockSub/skuIds")
    public R stockBySkuIdsSubStock(@RequestBody Map<Long, Long> skuIdAndNum) {
        skuIdAndNum.forEach((skuId, num) -> {
            boolean updated = wareSkuService.lambdaUpdate()
                    .eq(WareSkuEntity::getSkuId, skuId)
                    .setSql(String.format("stock=stock-%d", num))
                    .update();

            if (!updated) log.info("库存扣减失败");
        });

        return R.ok().put("data", "Stocks");
    }

    /**
     * 根据sku批量查询库存状态
     */
    @GetMapping("/stock/skuIds")
    public R stockBySkuIds(@RequestParam("skuIds") List<Long> skuIds) {
        // 去重
        skuIds = skuIds.stream().distinct().collect(Collectors.toList());
        List<WareSkuEntity> wareSkuEntities = new ArrayList<>();
        for (Long skuId : skuIds) {
            R wareSkuToR = infoBySkuId(skuId);
            wareSkuEntities.add(wareSkuToR.getData(WareSkuEntity.class));
        }

        Map<Long, Boolean> Stocks = wareSkuEntities.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toMap(
                        WareSkuEntity::getSkuId,
                        wareSkuEntity -> wareSkuEntity.getStock() > 0,
                        (existing, replacement) -> existing)
                );

        return R.ok().put("data", Stocks);
    }


    /**
     * 根据skuId获取信息
     */
    @GetMapping("/info/stock/{skuId}")
    public R infoBySkuId(@PathVariable("skuId") Long skuId) {
        List<WareSkuEntity> wareSkuEntities = wareSkuService.lambdaQuery()
                .eq(WareSkuEntity::getSkuId, skuId)
                .ge(WareSkuEntity::getStock, 0)
                .list();

        if (wareSkuEntities == null || wareSkuEntities.isEmpty()) {
            WareSkuEntity wareSku = new WareSkuEntity();
            wareSku.setSkuId(skuId);
            wareSku.setStock(0);
            return R.ok().put("data", wareSku);
        }

        Integer stock = wareSkuEntities.stream().mapToInt(WareSkuEntity::getStock).sum();
        Integer stockLocked = wareSkuEntities.stream().mapToInt(WareSkuEntity::getStockLocked).sum();
        WareSkuEntity wareSku = new WareSkuEntity();
        wareSku.setSkuId(skuId);
        wareSku.setStock(stock - stockLocked);

        return R.ok().put("data", wareSku);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    //@RequiresPermissions("ware:waresku:save")
    public R save(@RequestBody WareSkuEntity wareSku) {
        wareSkuService.save(wareSku);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    //@RequiresPermissions("ware:waresku:update")
    public R update(@RequestBody WareSkuEntity wareSku) {
        wareSkuService.updateById(wareSku);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    //@RequiresPermissions("ware:waresku:delete")
    public R delete(@RequestBody Long[] ids) {
        wareSkuService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
